package com.pine.dbant.core.service.impl;

import com.github.sd4324530.jtuple.Tuple2;
import com.pine.dbant.common.model.CommandStatement;
import com.pine.dbant.common.model.SQLStatement;
import com.pine.dbant.common.plugin.*;
import com.pine.dbant.core.entity.Connection;
import com.pine.dbant.core.service.BasePluginService;
import com.pine.dbant.core.service.SqlDatabaseService;
import com.pine.sunflower.core.utils.Strings;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoyuan
 * @create 2022/11/30 10:12
 **/
@Service
public class SqlDatabaseServiceImpl extends BasePluginService implements SqlDatabaseService {
//    @Override
//    public Table getTableMeta(Long connId, String catalog, String schema, String tableName) {
//        Tuple2<Connection, DatabasePlugin> databasePluginTuple2 = buildDatabasePlugin(connId);
//        databasePluginTuple2.first.setDbName(catalog);
//        JdbcMetadataAnalysis metadataAnalysis = (JdbcMetadataAnalysis) databasePluginTuple2.second.createMetadataAnalysis(databasePluginTuple2.first);
//       // return metadataAnalysis.getTableDetail(catalog, schema, tableName);
//        return null;
//    }

    @Override
    public QueryExecuteRecord queryDataOneTable(Long connId, String catalog, String schema, String tableName) {
        ExecuteParams queryExecuteRecord = new QueryExecuteParams();
        queryExecuteRecord.setScript(Strings.format("select * from {}", tableName));
        Tuple2<Connection, DatabasePlugin> databasePluginTuple2 = buildDatabasePlugin(connId);
        DatabasePlugin databasePlugin = databasePluginTuple2.second;
        databasePluginTuple2.first.setDbName(catalog);
        Connector connector = databasePlugin.createConnection(databasePluginTuple2.first);
        List<QueryExecuteRecord> queryExecuteRecords = new ArrayList<>();
        connector.execute(queryExecuteRecord, (ExecuteCallback<QueryExecuteRecord, SQLStatement>) executeRecord -> queryExecuteRecords.add(executeRecord));
        return queryExecuteRecords.isEmpty() ? null : queryExecuteRecords.get(0);
    }

    @Override
    public List<ExecuteRecord> executeScript(Long connId, String catalog, String schema, ExecuteParams executeParams) {
        Tuple2<Connection, DatabasePlugin> databasePluginTuple2 = buildDatabasePlugin(connId);
        DatabasePlugin databasePlugin = databasePluginTuple2.second;
        databasePluginTuple2.first.setDbName(catalog);
        Connector connector = databasePlugin.createConnection(databasePluginTuple2.first);
        List<ExecuteRecord> queryExecuteRecords = new ArrayList<>();
        connector.execute(executeParams, (ExecuteCallback<ExecuteRecord, CommandStatement>) executeRecord -> queryExecuteRecords.add(executeRecord));
        return queryExecuteRecords;
    }
}
